"""
参数工具
用于用户注册、登录、窗口管理、坐标配置等辅助功能
"""
import sys
import platform
import json
import pyperclip
from PIL import Image, ImageGrab
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow, QLineEdit, QPushButton, QMessageBox

from config.settings import Config
from common.tools.is_null import is_null
from common.tools.selection_window import RegionSelectorDialog
import win32con
import win32gui
import requests

# 隐藏控制台窗口
if sys.platform == 'win32':
    import ctypes
    whnd = ctypes.windll.kernel32.GetConsoleWindow()
    if whnd != 0:
        ctypes.windll.user32.ShowWindow(whnd, 0)

# 打包命令（在项目根目录执行，不显示控制台）：
# pyinstaller --onefile --noconsole --icon=files/icon/Setting.ico --paths=. apps/param_tool.py


def get_window_handle(window_title):
    """获取窗口句柄"""
    return win32gui.FindWindow(None, window_title)


def set_window_size(handle, width, height):
    """设置窗口大小"""
    win32gui.SetWindowPos(handle, win32con.HWND_TOP, 0, 0, width, height, win32con.SWP_SHOWWINDOW)


def move_window(handle, x, y):
    """移动窗口位置"""
    win32gui.SetWindowPos(handle, win32con.HWND_TOP, x, y, 0, 0, win32con.SWP_NOSIZE)




class ParamToolWindow(QMainWindow):
    """参数工具主窗口"""
    
    def __init__(self):
        super().__init__()
        
        # 初始化所有控件
        self.btn_move_game = QPushButton('移动游戏窗口', self)
        self.btn_move_movie = QPushButton('移动电影和电视', self)
        self.btn_move_pot = QPushButton('移动PotPlayer', self)
        self.input_username = QLineEdit(self)
        self.input_password = QLineEdit(self)
        self.input_key_bord = QLineEdit(self)
        self.btn_save_info = QPushButton('保存数据', self)
        self.btn_register = QPushButton('注册', self)
        self.btn_update_mac = QPushButton('解绑', self)
        self.input_open_vip = QLineEdit(self)
        self.btn_open_vip = QPushButton('开通AI', self)
        self.input_renewal = QLineEdit(self)
        self.btn_renewal = QPushButton('续费', self)
        self.input_x1 = QLineEdit(self)
        self.input_y1 = QLineEdit(self)
        self.input_x2 = QLineEdit(self)
        self.input_y2 = QLineEdit(self)
        self.input_x3 = QLineEdit(self)
        self.input_y3 = QLineEdit(self)
        self.input_x4 = QLineEdit(self)
        self.input_y4 = QLineEdit(self)
        self.input_x5 = QLineEdit(self)
        self.input_y5 = QLineEdit(self)
        self.input_x6 = QLineEdit(self)
        self.input_y6 = QLineEdit(self)
        self.btn_question = QPushButton('查看题目截图', self)
        self.btn_option = QPushButton('查看选项截图', self)
        self.btn_info = QPushButton('查看信息截图', self)
        self.btn_select_region = QPushButton('选择区域', self)
        self.btn_copy = QPushButton('复制坐标', self)
        
        self.init_ui()
    
    def init_ui(self):
        """初始化 UI"""
        self.setWindowTitle('设置工具')
        self.setWindowIcon(QIcon("files/icon/Setting.ico"))
        self.setGeometry(0, 0, 550, 275)  # 增加窗口高度
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        
        # 窗口移动按钮
        self._setup_window_buttons()
        
        # 账号信息区域
        self._setup_account_section()
        
        # 注册和解绑按钮
        self._setup_register_section()
        
        # VIP 和续费区域
        self._setup_vip_section()
        
        # 坐标输入区域
        self._setup_coordinate_section()
        
        # 截图按钮区域
        self._setup_screenshot_section()
        
        # 加载配置
        self.load_config()
    
    def _setup_window_buttons(self):
        """设置窗口移动按钮"""
        self.btn_move_game.clicked.connect(self.move_game_window)
        self.btn_move_game.setFixedSize(255, 50)
        self.btn_move_game.move(10, 10)
        
        self.btn_move_movie.clicked.connect(self.move_movie_window)
        self.btn_move_movie.setFixedSize(120, 50)
        self.btn_move_movie.move(275, 10)
        
        self.btn_move_pot.clicked.connect(self.move_pot_window)
        self.btn_move_pot.setFixedSize(120, 50)
        self.btn_move_pot.move(410, 10)
    
    def _setup_account_section(self):
        """设置账号信息区域"""
        self.input_username.setPlaceholderText('账号')
        self.input_username.setFixedSize(120, 25)
        self.input_username.move(10, 70)
        
        self.input_password.setPlaceholderText('密码')
        self.input_password.setFixedSize(120, 25)
        self.input_password.move(145, 70)
        
        self.input_key_bord.setPlaceholderText('按键')
        self.input_key_bord.setFixedSize(120, 25)
        self.input_key_bord.move(275, 70)
        
        self.btn_save_info.clicked.connect(self.save_config)
        self.btn_save_info.setFixedSize(120, 25)
        self.btn_save_info.move(410, 70)
    
    def _setup_register_section(self):
        """设置注册和解绑区域"""
        self.btn_register.clicked.connect(self.register)
        self.btn_register.setFixedSize(255, 25)
        self.btn_register.move(10, 105)
        
        self.btn_update_mac.clicked.connect(self.update_mac)
        self.btn_update_mac.setFixedSize(255, 25)
        self.btn_update_mac.move(275, 105)
    
    def _setup_vip_section(self):
        """设置 VIP 和续费区域"""
        self.input_open_vip.setPlaceholderText('开通AI卡密粘这里')
        self.input_open_vip.setFixedSize(120, 25)
        self.input_open_vip.move(10, 140)
        
        self.btn_open_vip.clicked.connect(self.open_vip)
        self.btn_open_vip.setFixedSize(120, 25)
        self.btn_open_vip.move(145, 140)
        
        self.input_renewal.setPlaceholderText('续费卡密粘贴这里')
        self.input_renewal.setFixedSize(120, 25)
        self.input_renewal.move(275, 140)
        
        self.btn_renewal.clicked.connect(self.renewal)
        self.btn_renewal.setFixedSize(120, 25)
        self.btn_renewal.move(410, 140)
    
    def _setup_coordinate_section(self):
        """设置坐标输入区域"""
        # 第一行：x1,y1,x2,y2
        coordinates_row1 = [
            (self.input_x1, 'x1', 10, 175),
            (self.input_y1, 'y1', 75, 175),
            (self.input_x2, 'x2', 145, 175),
            (self.input_y2, 'y2', 210, 175),
        ]
        
        # 第二行：x3,y3,x4,y4
        coordinates_row2 = [
            (self.input_x3, 'x3', 10, 205),
            (self.input_y3, 'y3', 75, 205),
            (self.input_x4, 'x4', 145, 205),
            (self.input_y4, 'y4', 210, 205),
        ]
        
        # 第三行：x5,y5,x6,y6
        coordinates_row3 = [
            (self.input_x5, 'x5', 10, 235),
            (self.input_y5, 'y5', 75, 235),
            (self.input_x6, 'x6', 145, 235),
            (self.input_y6, 'y6', 210, 235),
        ]
        
        # 设置所有输入框
        for input_field, placeholder, x, y in coordinates_row1 + coordinates_row2 + coordinates_row3:
            input_field.setPlaceholderText(placeholder)
            input_field.setFixedSize(55, 25)
            input_field.move(x, y)
    
    def _setup_screenshot_section(self):
        """设置截图按钮区域"""
        # 第一行：信息截图，对应 x1,y1,x2,y2 行
        self.btn_info.clicked.connect(self.screenshot_info)
        self.btn_info.setFixedSize(120, 25)
        self.btn_info.move(275, 175)

        # 第二行：题目截图，对应 x3,y3,x4,y4 行
        self.btn_question.clicked.connect(self.screenshot_question)
        self.btn_question.setFixedSize(120, 25)
        self.btn_question.move(275, 205)

        # 第三行：选项截图，对应 x5,y5,x6,y6 行
        self.btn_option.clicked.connect(self.screenshot_option)
        self.btn_option.setFixedSize(120, 25)
        self.btn_option.move(275, 235)

        # 右侧：选择区域按钮
        self.btn_select_region.clicked.connect(self.select_region)
        self.btn_select_region.setFixedSize(120, 25)
        self.btn_select_region.move(410, 205)

        # 右侧：复制坐标按钮
        self.btn_copy.clicked.connect(self.copy_coordinates)
        self.btn_copy.setFixedSize(120, 25)
        self.btn_copy.move(410, 235)
    
    def move_game_window(self):
        """移动游戏窗口"""
        window_title = '星球：重启'
        try:
            window_handle = get_window_handle(window_title)
            set_window_size(window_handle, 1600, 900)
            move_window(window_handle, 10, 0)
        except Exception as e:
            self._show_window_error(e, '星球：重启')
    
    def move_movie_window(self):
        """移动电影和电视窗口"""
        window_title = '电影和电视'
        try:
            window_handle = get_window_handle(window_title)
            set_window_size(window_handle, 1614, 906)
            move_window(window_handle, 4, 0)
        except Exception as e:
            self._show_window_error(e, '电影和电视')
    
    def move_pot_window(self):
        """移动 PotPlayer 窗口"""
        window_title = '测试视频.mp4 - PotPlayer'
        try:
            window_handle = get_window_handle(window_title)
            set_window_size(window_handle, 1600, 900)
            move_window(window_handle, 10, 0)
        except Exception as e:
            self._show_window_error(e, 'PotPlayer')
    
    def _show_window_error(self, error, app_name):
        """显示窗口操作错误"""
        QMessageBox.warning(
            self, '提示',
            f'请仔细阅读错误提示和解决方法\n'
            f'错误提示：{str(error)}\n'
            f'解决方法：\n'
            f'拒绝访问：请使用管理员身份运行此程序！\n'
            f'无效的窗口句柄：请先启动【{app_name}】',
            QMessageBox.Ok
        )
    
    def save_config(self):
        """保存配置"""
        if is_null(self.input_username.text()) or is_null(self.input_password.text()) or is_null(self.input_key_bord.text()):
            QMessageBox.information(self, '提示', '账号、密码、按键不能为空！！！')
            return
        
        config = Config.load_config()
        config['账号'] = self.input_username.text()
        config['密码'] = self.input_password.text()
        config['快捷键'] = self.input_key_bord.text()
        
        Config.save_config(config)
        self.load_config()
        QMessageBox.information(self, '提示', '参数设置成功！', QMessageBox.Ok)
    
    def load_config(self):
        """加载配置"""
        config = Config.load_config()
        self.input_username.setText(config.get('账号', ''))
        self.input_password.setText(config.get('密码', ''))
        self.input_key_bord.setText(config.get('快捷键', 'space'))
    
    def register(self):
        """注册"""
        username = self.input_username.text()
        password = self.input_password.text()
        
        if is_null(username) or is_null(password):
            QMessageBox.information(self, '提示', '账号和密码不能为空！！！')
            return
        
        try:
            url = f"{Config.get_api_base_url()}/user/register"
            data = {
                "username": username,
                "password": password,
                "mac": platform.node()
            }
            headers = {'content-type': 'application/json'}
            response = requests.post(url, headers=headers, data=json.dumps(data))
            response_data = response.json()
            
            if response_data['status'] == 200:
                QMessageBox.information(
                    self, '提示',
                    '注册成功！\n本软件仅支持注册、开通和续费功能\n修改参数请前往web端'
                )
            else:
                QMessageBox.information(self, '提示', response_data['msg'])
        except Exception as e:
            QMessageBox.warning(self, '错误', f'注册失败：{str(e)}')
    
    def update_mac(self):
        """解绑 MAC"""
        username = self.input_username.text()
        password = self.input_password.text()
        
        if is_null(username) or is_null(password):
            QMessageBox.information(self, '提示', '账号和密码不能为空！！！')
            return
        
        try:
            url = f"{Config.get_api_base_url()}/user/update_mac"
            data = {
                "username": username,
                "password": password,
                "mac": platform.node()
            }
            headers = {'content-type': 'application/json'}
            response = requests.put(url, headers=headers, data=json.dumps(data))
            response_data = response.json()
            QMessageBox.information(self, '提示', response_data['msg'])
        except Exception as e:
            QMessageBox.warning(self, '错误', f'解绑失败：{str(e)}')
    
    def open_vip(self):
        """开通 VIP"""
        username = self.input_username.text()
        keyword = self.input_open_vip.text()
        
        if is_null(username) or is_null(keyword):
            QMessageBox.information(self, '提示', '账号和卡密不能为空！！！')
            return
        
        try:
            url = f"{Config.get_api_base_url()}/user/open_vip"
            params = {"username": username, "keyWord": keyword}
            response = requests.post(url, params=params)
            response_data = response.json()
            QMessageBox.information(self, '提示', response_data['msg'])
        except Exception as e:
            QMessageBox.warning(self, '错误', f'开通失败：{str(e)}')
    
    def renewal(self):
        """续费"""
        username = self.input_username.text()
        keyword = self.input_renewal.text()
        
        if is_null(username) or is_null(keyword):
            QMessageBox.information(self, '提示', '账号和卡密不能为空！！！')
            return
        
        try:
            url = f"{Config.get_api_base_url()}/user/activation"
            params = {"username": username, "keyWord": keyword}
            response = requests.put(url, params=params)
            response_data = response.json()
            QMessageBox.information(self, '提示', response_data['msg'])
        except Exception as e:
            QMessageBox.warning(self, '错误', f'续费失败：{str(e)}')
    
    def screenshot_question(self):
        """截取题目区域"""
        # 题目区域使用 x3,y3,x4,y4
        if is_null(self.input_x3.text()) or is_null(self.input_y3.text()) or \
           is_null(self.input_x4.text()) or is_null(self.input_y4.text()):
            QMessageBox.information(self, '提示', 'x3,y3,x4,y4不能为空！！！')
            return
        
        self._take_screenshot(
            int(self.input_x3.text()),
            int(self.input_y3.text()),
            int(self.input_x4.text()),
            int(self.input_y4.text()),
            '测试问题截图'
        )
    
    def screenshot_option(self):
        """截取选项区域"""
        # 选项区域使用 x5,y5,x6,y6
        if is_null(self.input_x5.text()) or is_null(self.input_y5.text()) or \
           is_null(self.input_x6.text()) or is_null(self.input_y6.text()):
            QMessageBox.information(self, '提示', 'x5,y5,x6,y6不能为空！！！')
            return
        
        self._take_screenshot(
            int(self.input_x5.text()),
            int(self.input_y5.text()),
            int(self.input_x6.text()),
            int(self.input_y6.text()),
            '测试选项截图'
        )
    
    def select_region(self):
        """打开区域选择窗口"""
        # 创建并显示区域选择对话框
        self.region_selector = RegionSelectorDialog(self)
        self.region_selector.show()
    
    def screenshot_info(self):
        """截取信息区域"""
        # 信息区域使用 x1,y1,x2,y2
        if is_null(self.input_x1.text()) or is_null(self.input_y1.text()) or \
           is_null(self.input_x2.text()) or is_null(self.input_y2.text()):
            QMessageBox.information(self, '提示', 'x1,y1,x2,y2不能为空！！！')
            return
        
        self._take_screenshot(
            int(self.input_x1.text()),
            int(self.input_y1.text()),
            int(self.input_x2.text()),
            int(self.input_y2.text()),
            '测试信息截图'
        )
    
    def _take_screenshot(self, x1, y1, x2, y2, name):
        """执行截图"""
        try:
            # 纠正坐标顺序，确保 left < right 且 top < bottom
            left, right = sorted([x1, x2])
            top, bottom = sorted([y1, y2])

            # 检查宽高是否有效
            if right <= left or bottom <= top:
                QMessageBox.information(self, '提示', '截图区域宽度或高度为0，请重新调整区域！', QMessageBox.Ok)
                return

            box = (left, top, right, bottom)
            screenshot = ImageGrab.grab(bbox=box)
            image_path = f'{Config.SCREENSHOT_DIR}/{name}.png'
            screenshot.save(image_path)
            image = Image.open(image_path)
            image.show()
        except FileNotFoundError:
            QMessageBox.information(self, '提示', '未找到该图像文件！', QMessageBox.Ok)
        except Exception as e:
            QMessageBox.information(self, '提示', f"发生错误：{str(e)}", QMessageBox.Ok)
    
    def copy_coordinates(self):
        """复制坐标"""
        coordinates = [
            self.input_x1.text(), self.input_y1.text(),
            self.input_x2.text(), self.input_y2.text(),
            self.input_x3.text(), self.input_y3.text(),
            self.input_x4.text(), self.input_y4.text(),
            self.input_x5.text(), self.input_y5.text(),
            self.input_x6.text(), self.input_y6.text()
        ]
        text_to_copy = ','.join(coordinates)
        
        try:
            pyperclip.copy(text_to_copy)
            QMessageBox.information(self, '提示', "复制成功，请粘贴到【我】配置中！")
        except Exception as e:
            QMessageBox.information(self, '提示', f"复制失败：{str(e)}")


def main():
    """主函数"""
    # 确保必要的文件和目录存在
    Config.ensure_files_exist()
    
    # 创建应用程序
    app = QApplication(sys.argv)
    
    # 创建并显示主窗口
    main_window = ParamToolWindow()
    main_window.show()
    
    # 运行应用程序
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
